package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.result.Result;
import com.example.demo.result.ResultFactory;
import com.example.demo.service.LoginService;
import com.example.demo.service.UserService;
import com.example.demo.tools.AES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    UserService userService;

    @Autowired
    LoginService loginService;

    @PostMapping("/into")
    public Result login(@RequestBody User requestUser){
        try {
            String id = requestUser.getCustomerId();
            String passswd = userService.selectById(id);
            if (passswd == null || passswd == "") {
                return ResultFactory.buildFailResult("用户名错误!");
            }
            String pd = requestUser.getPassWord();
            String pw=AES.code(pd);
            System.out.println(pw);
            if (!pw.equals(passswd))
                return ResultFactory.buildFailResult("密码错误!");
            loginService.insertLogin(id);
            int power=userService.selectPower(id);
            if(power==1)
                return ResultFactory.buildSuccessResult("common");
            if(power==2)
                return ResultFactory.buildSuccessResult("admin");
            if(power==3)
                return ResultFactory.buildSuccessResult("super");
            return ResultFactory.buildFailResult("错误!");
        }catch (Exception e){
            return ResultFactory.buildFailResult("错误!");
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody User requestUser){
        try {
            User user=new User();
            String passswd=userService.selectById(requestUser.getCustomerId());
            if (passswd == null || passswd == "") {
                String id=requestUser.getCustomerId();
                user.setCustomerId(id);
                String pw = AES.code(requestUser.getPassWord());
                user.setPassWord(pw);
                user.setUserName(requestUser.getUserName());
                user.setPhoneNumber(requestUser.getPhoneNumber());
                user.setAddress(requestUser.getAddress());
                user.setBalance("0");
                user.setPower(1);
                userService.insertUser(user);
                return ResultFactory.buildSuccessResult(id);
            }
            else{
                return ResultFactory.buildFailResult("用户名已存在!");
            }
        }catch (Exception e){
            return ResultFactory.buildFailResult("错误!");
        }
    }

}
